<template>
    <div class="home">
        <div class="header">
            <a-icon type="search" @click="goSearch" :style="{fontSize:'18px'}" />&emsp;
            <a-dropdown>
                <a-icon type="unordered-list" :style="{fontSize:'18px'}" />
                <a-menu slot="overlay">
                    <a-menu-item key="0" @click="clickMenu('delete')">删除图书</a-menu-item>
                    <a-menu-item key="1" @click="mergeBookCase(true)">同步数据</a-menu-item>
                </a-menu>
            </a-dropdown>
        </div>

        <div v-if="books.length===0">
            <div class="nobook">书架还是空的</div>
        </div>
        <a-list v-else class="bookCase" :data-source="books">
            <a-list-item slot="renderItem" slot-scope="item">
                <router-link class="book"
                    :to="{path:'/reader',query:{bookUrl:item.url,bookName:item.bookName,currentChapter:item.currentChapter}}">
                    <div class="pic">
                        <img :src="'https://www.81book.com'+item.picUrl" alt />
                    </div>
                    <div class="txt">
                        <span class="title">{{item.bookName}}</span>
                        <span class="author">{{item.author}}</span>
                        <span class="lastChapter">最新章节：{{item.lastChapterName}}</span>
                    </div>
                    <div class="delate" v-show="showRemove">
                        <a-icon type="delete" :style="{color:'#f81d22',fontSize:'24px'}"
                            @click.stop="delate(item.url)" />
                        <!-- <img src="../assets/remove.png" alt @click.stop="delate(item.url)" /> -->
                    </div>
                </router-link>
            </a-list-item>
        </a-list>
        <Footer></Footer>
        <transition name="bottom">
            <div v-if="showBottom" class="bottom">
                <a-button type="danger" ghost @click="deleteAllBook">全部删除</a-button>
                <a-button @click="hideBottom">完成</a-button>
            </div>
        </transition>
    </div>
</template>

<script>
import Footer from "../components/Footer.vue";
import {
    Button,
    Icon,
    Dropdown,
    Menu,
    Modal,
    List,
    message,
} from "ant-design-vue";
import { getBookInfo, getBookCase, updateBookCase } from "@/api/index.js";

export default {
    data: () => {
        return {
            bookCase: [],
            books: [],
            removeBtn: "管理",
            showRemove: false,
            formData: {
                keyword: "",
            },
            showBottom: false,
        };
    },
    components: {
        Footer,
        "a-button": Button,
        "a-icon": Icon,
        "a-dropdown": Dropdown,
        "a-menu": Menu,
        "a-menu-item": Menu.Item,
        "a-list": List,
        "a-list-item": List.Item,
    },
    created() {
        let bookCase = localStorage.getItem("bookCase");
        if (bookCase) {
            let books = JSON.parse(bookCase);
            // this.getBooks(this.bookCase);
            // console.log(books);
            this.books = books;
        } else {
            localStorage.setItem("bookCase", JSON.stringify([]));
        }
        this.mergeBookCase();
    },
    methods: {
        getBooks(bookCase) {
            if (bookCase.length == 0) {
                return;
            } else {
                for (let item of bookCase) {
                    getBookInfo({
                        url: item.bookUrl,
                    }).then((res) => {
                        let book = res.data[0];
                        book.currentChapter = item.currentChapter;
                        this.books.push(book);
                    });
                }
            }
        },
        remove() {
            if (this.removeBtn === "管理") {
                this.showRemove = true;
                this.removeBtn = "完成";
            } else if (this.removeBtn === "完成") {
                this.showRemove = false;
                this.removeBtn = "管理";
            }
        },
        search() {
            this.$router.push({
                path: "/search",
                query: { keyword: this.formData.keyword },
            });
        },
        goSearch() {
            this.$router.push({ path: "/search" });
        },
        delate(bookUrl) {
            let newBookcase = [];
            // 从local中删除
            for (let item of this.bookCase) {
                if (item.bookUrl != bookUrl) {
                    newBookcase.push(item);
                }
            }
            this.bookCase = newBookcase;
            localStorage.setItem("bookCase", JSON.stringify(newBookcase));
            //  从books中删除
            let newBooks = [];
            for (let item of this.books) {
                if (item.url != bookUrl) {
                    newBooks.push(item);
                }
            }
            this.books = newBooks;
            if (localStorage.getItem("user")) {
                let userid = JSON.parse(localStorage.getItem("user")).userid;
                updateBookCase({
                    userid: userid,
                    books: JSON.stringify(this.books),
                });
            }
        },
        // 点击菜单
        clickMenu(type) {
            if (type === "delete") {
                this.showBottom = true;
                this.showRemove = true;
            }
        },
        // 删除所有图书
        deleteAllBook() {
            let me = this;
            Modal.confirm({
                title: "提示",
                content: "你确定要删除所有图书吗？",
                onOk() {
                    localStorage.setItem("bookCase", "[]");
                    me.books = [];
                    me.showBottom = false;
                    if (localStorage.getItem("user")) {
                        let userid = JSON.parse(
                            localStorage.getItem("user")
                        ).userid;
                        updateBookCase({
                            userid: userid,
                            books: JSON.stringify(me.books),
                        });
                    }
                },
                onCancel() {
                    me.showBottom = false;
                },
            });
        },
        hideBottom() {
            this.showBottom = false;
            this.showRemove = false;
        },
        async mergeBookCase(showMessage) {
            let localBooks = [...this.books];
            let remoteBooks = [];
            let userid;
            if (localStorage.getItem("user")) {
                userid = JSON.parse(localStorage.getItem("user")).userid;
            }
            if (!userid) return;
            let res = await getBookCase({ userid });
            if (Array.isArray(res.data) && res.data.length > 0) {
                remoteBooks = JSON.parse(res.data[0].books);
            }
            console.log('本地',localBooks);
            console.log('远程',remoteBooks);
            let newBooks = [...localBooks];
            for (let remote of remoteBooks) {
                let has = false;
                for (let local of localBooks) {
                    if (local.url === remote.url) {
                        has = true;
                    }
                }
                if (!has) {
                    newBooks.push(remote);
                }
            }
            this.books = newBooks;
            localStorage.setItem('bookCase',JSON.stringify(this.books))
            updateBookCase({
                userid: userid,
                books: JSON.stringify(newBooks),
            }).then((res) => {
                // console.log(res);
                if (res.data && res.data.code === 200 && showMessage) {
                    message.success("同步成功");
                }
            });
        },
    },
};
</script>

<style scoped lang='less'>
@media screen and (max-width: 420px) {
    .bottom {
        height: 50px;
        width: 100%;
        position: fixed;
        bottom: 0;
        background: white;
        display: flex;
        justify-content: space-around;
    }
    .bottom-enter-active,
    .bottom-leave-active {
        transition: all 1s;
    }
    .bottom-enter,
    .bottom-leave-to {
        transform: translateY(50px);
    }

    .home {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }
    .header {
        width: 100%;
        height: auto;
        padding: 15px;
        display: flex;
        justify-content: flex-end;
    }
    .head {
        width: 100%;
        display: flex;
        height: 10%;
        overflow: hidden;
        justify-content: space-around;
    }
    .head form {
        /* text-align: center; */
        width: 70%;
        display: flex;
        overflow: hidden;
    }
    .remove {
        // width: 20%;
    }
    .remove button {
        margin: 5px;
    }
    .search img {
        width: 30px;
        height: 30px;
    }

    .nobook {
        text-align: center;
        padding-top: 50%;
    }
    .bookCase {
        overflow: auto;
        height: 80%;
    }

    .book {
        display: flex;
        flex-direction: row;
        /* margin-left: 20px; */
        margin-bottom: 10px;
        width: 95%;
        margin: 0 auto;
        color: black;
    }
    .pic {
        width: 20%;
        min-height: 80px;
        background: url(../assets/cover.jpg);
        background-size: 100% 100%;
    }
    .txt {
        display: flex;
        flex-direction: column;
        margin-left: 10px;
        width: 70%;
    }
    .book img {
        width: 100%;
    }
    .txt span {
        line-height: 1.5;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    .title {
        margin-top: 20px;
        font-size: 16px;
    }
    .delate {
        display: flex;
        align-items: center;
        width: 20px;
    }

    .delate img {
        width: 20px;
    }
}

@media screen and (min-width: 420px) {
    .nobook {
        text-align: center;
        padding-top: 50%;
    }
    .head {
        display: flex;
        justify-content: center;
        .remove {
            margin-left: 300px;
        }
    }
    .bookCase {
        display: flex;
        flex-wrap: wrap;
        padding-top: 20px;
        .book {
            width: 1100px;
            height: 150px;
            margin-bottom: 10px;
            display: flex;
            color: black;

            .pic {
                width: 100px;
                height: 150px;
                background: url(../assets/cover.jpg);
                background-size: 100% 100%;
                img {
                    width: 100%;
                    height: 100%;
                }
            }
            .txt {
                height: 150px;
                margin-left: 10px;
                width: 900px;
                display: flex;
                flex-direction: column;
                justify-content: flex-end;
                span {
                    margin-bottom: 10px;
                }
            }
            .delate {
                width: 30px;
                height: 30px;
                margin-top: 30px;
                img {
                    width: 100%;
                    height: 100%;
                }
            }
        }
    }
}
</style>